﻿var $edittr;
var databasetypelist = GetDbDataType();

$(function () {

    var updateselect = function () {
        var list = GetDbDataType();
        var options = "";
        for (var i = 0; i < databasetypelist.length; i++) {
            options += ("<option  value='" + JSON.stringify(databasetypelist[i]) + "'>" + databasetypelist[i].Name + "</option>");
        }
        $("#update-column-DataTypeSelect").append(options);
        $("#add-column-DataTypeSelect").append(options);
    }

    $("#Create-Form").validate({
        submitHandler: function (form) {
            var trlist = $("#table-column-details tbody tr");
            if (trlist.length > 0) {
                var str = "";
                for (var i = 0; i < trlist.length; i++) {
                    var tempjson = JSON.parse($(trlist[i]).attr("data"));
                    str += (tempjson.name + ",");
                    str += (tempjson.type + ",");
                    str += (tempjson.length + ",");
                    str += tempjson.isnull + ",";
                    str += tempjson.description ;
                    if (i != (trlist.length - 1)) {
                        str += ",";
                    }
                }
                $("#ColumnSettings").val(str);
                $.ajax({
                    url: apiUrl,
                    type: "Post",
                    dataType: "json",
                    data: $("#Create-Form").serialize(),
                    success: function (data) {
                        if (data.IsSccuess) {
                            ShowGritter("保存成功", 2, "DataTableManagement.html");
                        } else {
                            if (IsLogined(data.ErrorCode)) {
                                alert("失败（" + "错误代码：" + data.ErrorCode + "，错误信息：" + data.Message + ")");
                            }
                        }
                    },
                    beforeSend: function () {
                        ShowGritter("提交中");
                    }
                });
            } else {
                ShowGritter("新建列后再保存！");
            }


        }
    });
    $("#add-column-form").validate({
        submitHandler: function (form) {
            var jsonobj = {};
            jsonobj.name = $("#add-column-Name").val();
            jsonobj.length = $("#add-column-Length").val();
            jsonobj.type = JSON.parse($("#add-column-DataTypeSelect").val()).Name;
            jsonobj.isnull = $("#add-column-nullselect").val() == "true" ? true : false;
            jsonobj.description = $("#add-column-Description").val().replace(",", "，");
            $("#table-column-details").append(AssembleData(jsonobj));
            $('#add-column-modal').modal('hide');
            ShowGritter("新增成功");
            console.log(JSON.stringify(jsonobj));
        }
    });
    $("#update-column-form").validate({
        submitHandler: function (form) {
            try {
                var jsonobj = {};
                jsonobj.name = $("#update-column-Name").val();
                jsonobj.length = $("#update-column-Length").val();
                jsonobj.type = JSON.parse($("#update-column-DataTypeSelect").val()).Name;
                jsonobj.isnull = $("#update-column-nullselect").val() == "true" ? true : false;
                jsonobj.description = $("#update-column-Description").val().replace(",", "，");
                if ($edittr != null) {
                    $(AssembleData(jsonobj)).replaceAll($edittr);
                    ShowGritter("编辑成功");
                    console.log(JSON.stringify(jsonobj));
                } else {
                    ShowGritter("编辑失败");
                }
                $('#update-column-modal').modal('hide');
            } catch (e) {
                console.log(e);
            }
        }
    });
    updateselect();
});
//组合数据
var AppadData = function (data) {
    var list = new Array();
    var trlist = "";
    for (var i = 0; i < data.length; i++) {
        var $this = data[i];
        trlist += AssembleData({ name: name, length: data[i].Length, type: $this.Type, description: $this.Description == undefined ? "" : $this.Description, isnull: "" });
    }
    $("#table-column-details").append(trlist);
}
//传入data对象返回一行的表格数据
var AssembleData = function (data) {
    var tr = "<tr data='" + JSON.stringify(data) + "'><td>";
    tr += (data.name + "</td>");
    tr += ("<td>" + data.type + "</td>");
    tr += ("<td>" + data.length + "</td>");
    tr += ("<td>" + data.description + "</td>");//备注
    tr += ("<td>" + ((data.isnull || data.isnull == "true") ? "是" : "否") + "</td>");//是否为空
    tr += ("<td>  <a href='javascript:void(0)' onclick=\"UpateData(this)\"><i class='fa fa-pencil-square-o '></i>编辑</a>&nbsp;<a href='javascript:void(0)' onclick=\"DeleteData(this)\"><i class='fa  fa-times-circle'></i>删除</a></td></tr>");
    return tr;
}
var DeleteData = function (obj) {
    if (confirm("是否删除？")) {
        $(obj).parent().parent().remove();
    }
}
var AddData = function () {
    document.getElementById("add-column-form").reset();
    $("#add-column-modal").modal({ show: true });
    $("#add-column-Length").val(0);

}
var UpateData = function (obj) {
    var tr = $(obj).parent().parent();
    $edittr = tr;
    var json = tr.attr("data");
    var jsonobj = JSON.parse(json);
    $("#update-column-Name").val(jsonobj.name);
    var dataTypeSelectobj = {}
    dataTypeSelectobj.Name = jsonobj.type;
    if (jsonobj.type != "nvarchar") {
        dataTypeSelectobj.NeedLength = false;
    } else {
        dataTypeSelectobj.NeedLength = true;
    }
    $("#update-column-DataTypeSelect").val(JSON.stringify(dataTypeSelectobj));
    $("#update-column-Length").val(jsonobj.length);
    $("#update-column-nullselect").val(jsonobj.isnull.toString());
    $("#update-column-Description").val(jsonobj.description);
    $('#update-column-modal').modal({
        show: true
    });
}
var dtcoltypeChange = function (obj) {
    var $this = $(obj);
    var tempjson = JSON.parse($this.val());
    var lengthtext = $this.parent().parent().next().children("[class='input']").children();
    if (tempjson.NeedLength) {
        lengthtext.removeAttr("disabled");
    } else {
        lengthtext.val("0");
        lengthtext.attr("disabled", "disabled");
    }
}